package org.cbyyx.tc.exception;

import lombok.extern.slf4j.Slf4j;
import org.cbyyx.tc.common.BaseResponse;
import org.cbyyx.tc.enums.ErrorCode;
import org.cbyyx.tc.common.ResultUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> handleException(MethodArgumentNotValidException e) {
        log.error("参数错误", e);
        return ResultUtils.error(ErrorCode.PARAMS_ERROR, e.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> handleException(BusinessException e, HttpServletResponse response) {
        log.error("业务异常", e);
        response.setStatus(e.getCode()/100);
        return ResultUtils.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public BaseResponse<?> handleException(Exception e, HttpServletResponse response) {
        log.error("系统异常", e);
        response.setStatus(500);
        return ResultUtils.error(ErrorCode.SYSTEM_ERROR);
    }
}
